package com.waa.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.waa.gulimall.common.constant.ProductConstant;
import com.waa.gulimall.common.to.SkuReductionTo;
import com.waa.gulimall.common.to.SpuBoundTo;
import com.waa.gulimall.common.to.es.SkuEsModel;
import com.waa.gulimall.common.utils.R;
import com.waa.gulimall.product.entity.*;
import com.waa.gulimall.product.feign.CouponFeignService;
import com.waa.gulimall.product.feign.SearchFeginService;
import com.waa.gulimall.product.feign.WareFeignService;
import com.waa.gulimall.product.service.*;
import com.waa.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waa.gulimall.common.utils.PageUtils;
import com.waa.gulimall.common.utils.Query;

import com.waa.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

//TODO 高级部分完善
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private  BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SearchFeginService searchFeginService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

   //TODO 高级部分完善

    @Transactional
    @Override
    public void save(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息 pms_spu_info
        final SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2.保存spu描述图片 pms_spu_info_desc
        final List<String> decript = spuSaveVo.getDecript();
        final SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);
        //3.保存spu的图片集 pms_spu_images
        final List<String> voImages = spuSaveVo.getImages();
        this.addSpuImages(voImages, spuInfoEntity.getId());
        //4.保存spu的规格参数 pms_product_attr_value
        final List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        this.addbaseAttrs(baseAttrs, spuInfoEntity.getId());


        //保存spu的积分信息：gulimall_sms\sms_spu_bounds
        final Bounds bounds = spuSaveVo.getBounds();
        final SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.saveSpuBounds(spuBoundTo);


        //5.保存当前spu对应的所有sku信息
        //5.1 sku的基本信息：pms_sku_info
        final List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                final SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //5.2 sku的图片信息： pms_sku_images
                final List<SkuImagesEntity> skuImageList = item.getImages().stream().map(img -> {
                    final SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(imgfilter -> {
                    return !imgfilter.getImgUrl().isEmpty();
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImageList);
                //5.3 sku的销售属性信息：pms_sku_sale_attr_value
                final List<Attr> attr = item.getAttr();
                final List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attr.stream().map(a -> {
                    final SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                //5.4 sku的优惠满减信息：gulimall_sms=>sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                final SkuReductionTo skuReduction = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReduction);
                skuReduction.setSkuId(skuInfoEntity.getSkuId());
                if (skuReduction.getFullCount()>0 || skuReduction.getFullPrice().compareTo(new BigDecimal("0"))==1 ){//判断它是否有满减或者打折优惠
                couponFeignService.saveSpuReduction(skuReduction);
                }

 /*
 * skuReductionTo = {SkuReductionTo@10355}
 skuId = {Long@12107} 8
 fullCount = 3
 discount = {BigDecimal@12108} "0.98"
 countStatus = 1
 fullPrice = {BigDecimal@12109} "10000"
 reducePrice = {BigDecimal@12110} "250"
 priceStatus = 1
 memberPrice = null
 * */
            });
            final SkuInfoEntity skuInfoEntity = new SkuInfoEntity();


        }


    }

    @Override
    public PageUtils queryPageBycondation(Map<String, Object> params) {

        final QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        final String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wapper)->{
                wapper.eq("id",key).or().like("spu_name",key );
            });
        };
        final String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.and((wapper)->{
                wapper.eq("publish_status",status);
            });
        }

        final String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            queryWrapper.and((wapper)->{
                wapper.eq("brand_id",brandId);
            });
        };
        final String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            queryWrapper.and((wapper)->{
                wapper.eq("catalog_id",catelogId);
            });
        }
        final IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    //商品上架
    @Override
    public void up(Long spuId) {
             //查出spuId對應的所有sku信息，品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuid(spuId);
             //TODO 查出当前SKU的所有可以被用来检索的规格属性
        final List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrlistforspu(spuId);
        final List<Long> attrIds = productAttrValueEntities.stream().map(item -> {
            final Long attrId = item.getAttrId();
            return attrId;
        }).collect(Collectors.toList());
        final List<Long> searchAttrIds = attrService.getBaseMapper().selectList(new QueryWrapper<AttrEntity>().in("attr_id", attrIds).and(item -> {
            item.eq("search_type", 1);
        })).stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        final HashSet<Long> hashSet = new HashSet<>(searchAttrIds);
        final List<SkuEsModel.Attr> attrlist = productAttrValueEntities.stream().filter(item -> {
            return hashSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attr attrs = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());
        //TODO 发送远程调用访问库存，判断库存中还有没有
        //获取所有skuId
        final List<Long> skuIds = skus.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());
          Map<Long, Boolean> map = null;
        try{
            final R<List<SkuHasStockVo>> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            map= skuHasStock.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
          log.error("远程调用出现异常{}",e);
        }
        //组装所需要的数据
         final Map<Long, Boolean> map1 = map;
        final List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            final SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //判断库存中还有没有
            skuEsModel.setHasStock(map1==null?true:map1.get(sku.getSkuId()));
            //TODO 热度评分，默认0
            skuEsModel.setHotScore(0L);
            //TODO 查询品牌和分类的名字信息
            final BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            final CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrlist);
            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 将数据发给ES进行数据保存
        final R r = searchFeginService.productStatusUp(upProducts);
        if (r.getCode() == 0)
            //远程调用成功
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        else {
            //远程调用失败
            //Todo 重複調用問題
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        final SkuInfoEntity infoEntity = skuInfoService.getById(skuId);

        final SpuInfoEntity spuInfoEntity = getById(infoEntity.getSpuId());

        return spuInfoEntity;
    }

    private void addbaseAttrs(List<BaseAttrs> baseAttrs, Long id) {
        final List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            final ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            final AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setSpuId(id);
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
    }

    private void addSpuImages(List<String> voImages, Long id) {
        if (!CollectionUtils.isEmpty(voImages)) {
            final List<SpuImagesEntity> collect = voImages.stream().map(item -> {
                final SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(id);
                spuImagesEntity.setImgUrl(item);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }

    }

}